package com.xgzit.xgzmall.order.config;

import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.RequestContent;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * feign 调用会创建新的请求，导致请求头默认是 丢失的。
 * 使用拦截器给它加上
 * @Author xgz
 * @Date 2021-06-27 9:22
 */
@Slf4j
@Configuration
public class XgzMallFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){

        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {
                log.info("feign远程之前，拦截器工作");
                // spring 提供了一个 RequestContextHolder 上下文保持器，可以拿到 请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (Objects.nonNull(requestAttributes)){
                    HttpServletRequest request = requestAttributes.getRequest();
                    // 同步请求头数据
                    requestTemplate.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }
}
